package com.geely.club.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.security.MessageDigest;
import java.util.Random;

/**
 * Created by mengyangyang on 2015-10-15.
 */
public class Device {
    private static int width;
    private static int height;
    private static float density;
    private static String deviceId;
    private static boolean isInited = false;
    private static SharedPreferences sp;
    private static Context context;

    public static void init(Context c) {
        if (isInited) return;
        isInited = true;
        context = c.getApplicationContext();
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        sp = context.getSharedPreferences("Device", Context.MODE_PRIVATE);
        height = dm.heightPixels;
        width = dm.widthPixels;
        density = dm.density;
        deviceId = getUniqueID();
    }

    /**
     * @return 屏幕宽度
     */
    public static int getWidth() {
        return width;
    }

    /**
     * @return 屏幕高度
     */
    public static int getHeight() {
        return height;
    }

    public static int dip2px(float dpValue) {
        return (int) (dpValue * density + 0.5f);
    }

    public static int px2dip(float pxValue) {
        return (int) (pxValue / density + 0.5f);
    }

    public static String getDeviceId() {
        return deviceId;
    }

    // public static Context _context;
    public static String getUniqueID() {
        String devicieId = sp.getString("DevicieId", "");
        if (devicieId.equals("")) {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String _id = tm.getDeviceId();
            if (null != _id) {
                devicieId = getMD5String(_id).toLowerCase();
                sp.edit().putString("DeviceId", devicieId).commit();
            }
        }
        if (devicieId.equals("")) {
            File file = new File(context.getFilesDir().getParentFile() + "/.deviceid");
            if (file.exists()) {
                try {
                    FileInputStream fis = new FileInputStream(file);
                    InputStreamReader isr = new InputStreamReader(fis);
                    BufferedReader reader = new BufferedReader(isr);
                    devicieId = reader.readLine();
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (null == devicieId || devicieId.equals("")) {
                Random r = new Random();
                devicieId = getMD5String(System.currentTimeMillis() + "" + r.nextInt(Integer.MAX_VALUE)).toLowerCase();
                sp.edit().putString("DeviceId", devicieId).commit();
                try {
                    FileOutputStream fos = new FileOutputStream(file);
                    OutputStreamWriter osw = new OutputStreamWriter(fos);
                    BufferedWriter writer = new BufferedWriter(osw);
                    writer.write(devicieId);
                    writer.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        return devicieId;
    }

    public static String getMD5String(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法?MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要?
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
